package com.chengyi.serialport.demo.activity

import android.text.InputType
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.chengyi.serialboard.sdk.CYSerialboard
import com.chengyi.serialport.demo.databinding.ActivityMainBinding
import com.chengyi.serialport.demo.R
import com.chengyi.serialport.demo.adapter.MainActivityAdapter
import com.chengyi.serialport.demo.controller.AppController
import com.hjq.toast.Toaster
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.tencent.mmkv.MMKV
import com.wyj.controller.UIController
import com.wyj.databinding.BaseViewModel
import com.wyj.utils.QMUIDialogHelper
import me.goldze.mvvmhabit.binding.command.BindingCommand
import java.util.concurrent.atomic.AtomicBoolean

class ActivityMain : BaseActivity<ActivityMainBinding, ActivityMain.ViewModel>() {
    override fun getLayoutRes(): Int = R.layout.activity_main
    override fun initViews() {
        initBar(binding.myTopBar)
        binding.recyclerView.adapter = MainActivityAdapter(AppController.activityList).apply {
            this.onItemClickListener = BindingCommand { position ->
                val item = this.getItem(position) ?: return@BindingCommand
                if (item.activity == "secretInit") {
                    secretInit()
                    return@BindingCommand
                }
                if (secretInitAtom.get()) {
                    UIController.startActivity(vm, Class.forName("com.chengyi.serialport.demo.activity.${item.activity}"))
                } else {
                    Toaster.show("请先初始化")
                }
            }
        }
        if (QMUIDisplayHelper.getScreenWidth(this) > QMUIDisplayHelper.getScreenHeight(this)) {
            vm.columnCount.value = 4
        }
    }

    private val secretInitAtom = AtomicBoolean()

    private fun secretInit() {
        if (secretInitAtom.get()) {
            return
        }
        val originSecret = MMKV.defaultMMKV().decodeString("secret", "A09690556E118919AE7654A4D1BE576638978B4D9CBA73673E9E8EFF422B1D2D")
        QMUIDialogHelper.createEditDialog(this, "请输入密钥", InputType.TYPE_CLASS_TEXT, "请输入密钥", originSecret ?: "", false, object : QMUIDialogHelper.OnEditListener {
            override fun onEditListener(text: String) {
                CYSerialboard.init(text, object : CYSerialboard.Callback {
                    override fun onSuccess() {
                        MMKV.defaultMMKV().encode("secret", text)
                        Toaster.show("成功")
                        secretInitAtom.set(true)
                    }

                    override fun onFail(errCode: Int, errMsg: String) {
                        Log.e("secretInit", "初始化错误，code=${errCode}, msg=${errMsg}")
                    }
                })
            }
        }).show()
    }

    class ViewModel : BaseViewModel() {
        val columnCount = MutableLiveData(2)
    }
}